package cn.stronglink.assetmanage.business.check.view.wait;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.IOException;
import java.util.List;

import cn.stronglink.assetmanage.MainActivity;
import cn.stronglink.assetmanage.MyApplication;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.adapter.CheckListAdapter;
import cn.stronglink.assetmanage.business.check.model.CheckModel;
import cn.stronglink.assetmanage.business.check.model.WaitModel;
import cn.stronglink.assetmanage.business.check.presenter.WaitListPresenter;
import cn.stronglink.assetmanage.business.check.view.detail.AddCheckDetailFragment;
import cn.stronglink.assetmanage.business.inventory.view.IRefreshList;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.SyncTypes;
import cn.stronglink.assetmanage.index.base.BaseChildFragment;
import cn.stronglink.assetmanage.index.entity.PromissionEntity;
import cn.stronglink.assetmanage.index.view.onRecyclerListener;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ToastUtil;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 待入库表单列表
 */
public class WaitListFragment extends BaseChildFragment implements CheckModel.onCheckDataListener, IRefreshList {
    private WaitListView waitListView;
    //表单列表adapter
    private CheckListAdapter listAdapter;
    RecyclerView rv_checkwait_order_list;
    private WaitModel waitModel;
    private LinearLayoutManager layoutManager;
    private TextView txt_title_right, txt_title_left, txt_main_title;

    protected Activity mActivity;
    private List<Check> entityList;
    private SwipeRefreshLayout refresh_check_list;
    private CheckModel mCheckModel;

    @Nullable
    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_wait_list, container, false);
        initViewAndData(rootView);
        return rootView;
    }


    private void initViewAndData(View view) {
        try {
            txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
            txt_main_title.setText("验收入库");
            txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
            txt_title_right.setVisibility(View.INVISIBLE);
            txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
            txt_title_left.setVisibility(View.INVISIBLE);
            rv_checkwait_order_list = view.findViewById(R.id.rv_checkwait_order_list);
            listAdapter = new CheckListAdapter(getActivity());
            layoutManager = new LinearLayoutManager(this.getActivity(), LinearLayout.VERTICAL, false);
            rv_checkwait_order_list.setLayoutManager(layoutManager);
            rv_checkwait_order_list.setAdapter(listAdapter);
            listAdapter.setOnItemClickListener(new onRecyclerListener() {
                @Override
                public void onItemClicked(View v, int postion) {
                    if (entityList != null && entityList.size() > 0) {
                        MainActivity activity = (MainActivity) getActivity();
                        PromissionEntity pe = new PromissionEntity();
                        pe.setFragment(new WaitAssetFragment());
                        pe.setPosition(MainActivity.FRAGMENT_CUSTOM_ID);
                        pe.setTitle("待入库");
                        // 设置打开盘点详情后传递的参数
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constants.CHECK_IN_DETAIL_NO, entityList.get(postion).getId_());
                        pe.setBundle(bundle);
                        activity.onEventRegister(pe);
                    }
                }
            });
            waitListView = new WaitListView(this, view, listAdapter);
            waitModel = new WaitModel();
            mCheckModel = new CheckModel();
            refresh_check_list = view.findViewById(R.id.refresh_check_list);
            refresh_check_list.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    refreshView();
                }
            });
            this.refreshList();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.toastShort("没有数据显示");
        }
    }

    private void refreshView() {
        //判断是离线还是在线
        SyncTypes syncTypes = DaoManager.getDaoSession(this.getActivity()).getSyncTypesDao().
                queryBuilder().where(SyncTypesDao.Properties.IsSelected.eq(true)).unique();
        int tp = 0;
        if (syncTypes != null) {
            tp = syncTypes.getSyscTs();
        }
        switch (tp) {
            case Constants.STATUS_ONE:
                //自动
                if (!Constants.isGetCheckData) {
                    //每次进入页面都去服务器获取验收数据
                    Constants.isGetCheckData = true;
                    mCheckModel.getCheckData();
                    mCheckModel.setCheckDataListener(this);
                }
                break;
            case Constants.STATUS_TWO:
                //离线，从数据库拿数据
                if (refresh_check_list != null) {
                    refresh_check_list.setRefreshing(false);
                }
                ToastUtil.toastShort("本地数据加载完成");
                break;
        }
    }


    private void showWaitCheckData() {
        try {
            if (waitModel != null && waitListView != null) {
                entityList = waitModel.getDataByOrderNoDistince();
                waitListView.setListData(entityList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (refresh_check_list != null) {
            refresh_check_list.setRefreshing(false);
        }
    }

    @Override
    public void onFailer(Call call, final IOException ex) {
        if (this.mActivity != null) {
            this.mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (refresh_check_list != null) {
                        refresh_check_list.setRefreshing(false);
                    }
                    ToastUtil.toastShort(ex.getMessage());
                }
            });
        }
    }

    @Override
    public void onResponse(Call call, final Response response) {
        if (mActivity == null) {
            return;
        } else {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (refresh_check_list != null) {
                        refresh_check_list.setRefreshing(false);
                    }
                }
            });
        }
        try {
            //取消progress提示框
            if (response.isSuccessful()) {
                if (response.code() == 200) {
                    String json = response.body().string();
                    if (json != null && !"".equals(json)) {
                        mCheckModel.saveCheckData(json);
                        ToastUtil.toastShort("更新完成");
                        mActivity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showWaitCheckData();
                            }
                        });

                    } else {
                        ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_no_data));
                    }
                } else {
                    ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
                }
            } else {
                ToastUtil.toastShort(MyApplication.APP_CONTEXT.getString(R.string.get_data_fail));
            }
        } catch (Exception e) {
            ToastUtil.toastShort(e.getMessage());
        }
    }

    @Override
    public void refreshList() {
        showWaitCheckData();
    }
}
